/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：服务端要处理多个客户端的消息，需要用一个数组来维护所有的客户端的连接。每个客户端都有自己的Socket和缓冲区
* CreateTime：2020-08-14 13:47:44
* Version：1.0
* Modify Recorder：
*************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

namespace TinyToolKit.Network
{
    public class Conn
    {
        public Socket socket;
        public bool isUse;
        public Message message;
        public long lastTickTime = long.MinValue;
        public Player player;

        private IPEndPoint _ipEndPoint;
        
        public void Init(Socket socket,string id) 
        {
            this.socket = socket;
            isUse = true;
            message = new Message();
            player = new Player(id,this);

            lastTickTime = TinyUtility.Time.GetTimeStamp();
            _ipEndPoint = (IPEndPoint)socket.RemoteEndPoint;
        }

        public IPEndPoint GetAddress()
        {
            return !isUse ? null : _ipEndPoint;
        }

        public void Send(byte[] data)
        {
            byte[] tempData = message.PackMessage(data);
            socket.Send(tempData);
        }

        public void Send(string msg)
        {
            byte[] data = Encoding.UTF8.GetBytes(msg);
            byte[] tempData = message.PackMessage(data);
            socket.Send(tempData);
        }

        public void Close()
        {
            if (!isUse) return;
            isUse = false;
            
            PlayerConnEvent connEvent = new PlayerConnEvent();
            connEvent.OnLogout(player);
            
            socket.Close();
        }
    }
}

